import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "fs";
import path from "path";

/** nodejs 文件操作 */
const fileUtils = (ROOT_PATH = path.resolve('./')) => ({
  /** 检查文件是否存在
   * @param {string} filePath 文件路径
   * @example checkFile('src/index.ts') // true or false
   */
  checkFile(filePath: string) {
    return existsSync(path.resolve(`${ROOT_PATH}${filePath}`));
  },
  /** 读取文件内容
   * @param filePath 文件路径
   * @param isCreate 是否创建文件
   * @param option 读取配置
   * @example getFile('src/index.ts') // 'any...'
   */
  getFile(filePath: string, isCreate = false, option: Parameters<typeof readFileSync>[1] = 'utf-8') {
    const file = path.resolve(`${ROOT_PATH}${filePath}`);
    const fileType = filePath.split('.').pop() || '';

    if (existsSync(file)) {
      const res = readFileSync(file, option);

      if (/json/.test(fileType)) return JSON.parse(res as string);
      else return res;
    } else {
      if (isCreate) return this.writeFile(filePath, '');
      else throw new Error(`文件不存在：${filePath}`);
    }
  },
  /** 写入文件 */
  writeFile(...args: Parameters<typeof writeFileSync>) {
    const filePath = args[0]
    const file = path.resolve(`${ROOT_PATH}${filePath}`);

    // @ts-ignore
    writeFileSync(file, ...args.slice(1));
  },
  /** 头部写入文件
   * @param filePath
   * @param content
   */
  shiftFile(filePath: string, content: string) {
    this.writeFile(filePath, `${content}\n${this.getFile(filePath, true)}`);
  },
  /** 尾部写入文件
   * @param filePath 文件路径
   * @param content 内容
   */
  appendFile(filePath: string, content: string) {
    this.writeFile(filePath, `${this.getFile(filePath, true)}\n${content}`);
  },
  /** 删除文件
   * @type {typeof rmSync}
   */
  deleteFile(...args: Parameters<typeof rmSync>) {
    const file = path.resolve(`${ROOT_PATH}${args[0]}`)
    // @ts-ignore
    rmSync(file, ...args.slice(1));
  },
  /** 获取文件根目录
   * @param filePath 文件路径
   */
  getFileRootPath(filePath: string) {
    return path.resolve(`${ROOT_PATH}${filePath}`);
  },
  /** 复制文件
   * @type {typeof copyFileSync}
   */
  copyFileSync(...args: Parameters<typeof copyFileSync>) { return copyFileSync(...args) }
});

export default fileUtils;